package com.example.woke;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.http.HttpMethods;
import com.woke.method.Intentnet;
import com.woke.method.Mapupload;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

public class BorrowsureActivity extends Activity implements OnClickListener {

	private TextView mView1,mView2,mView3,mView4,mView5,mView6,mView7;
	private float floatExtra;
	private float floatExtra2;
	private int intExtra2;
	private String forwhy,intExtra;
	private CheckBox mBox;
	private TextView mTok;
	private String time;
	private ArrayList<String> photolist = new ArrayList<String>();
	private ArrayList<String> tosucdlist = new 	ArrayList<String>();;
	private MyApp myApp;
	private RelativeLayout mRelativ;
	private float shiji;
	private int ervicefee;
	private boolean isupload ;
	private int time1;
	private String jiekuanyontu= "";
	private String stringExtra;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_borrowsure);

		Intent intent = getIntent();
		floatExtra = intent.getFloatExtra("allmoney", 0);
		floatExtra2 = intent.getFloatExtra("lili", 0);
		intExtra = intent.getStringExtra("atime");
		forwhy = intent.getStringExtra("forwhy");	
		intExtra2 = intent.getIntExtra("adays", 0);
		stringExtra = intent.getStringExtra("stringExtra");
		time = Intentnet.getTime(intExtra);
		time1 = Integer.parseInt(time);
		ervicefee = intent.getIntExtra("parseInt", 1);
		shiji = intent.getFloatExtra("parseFloat", 1.0f);
		tosucdlist.add(""+floatExtra);
		tosucdlist.add(""+floatExtra2);
		tosucdlist.add(""+intExtra);
		tosucdlist.add(""+forwhy);
		tosucdlist.add(""+time);
		tosucdlist.add(""+ervicefee);
		photolist = intent.getStringArrayListExtra("photolist");
		myApp = (MyApp) getApplication();
		Log.e("time", "time"+time);
		intview();
	}

	private void intview() {
		mView1 = (TextView) findViewById(R.id.avsure_text_totalmoney);
		mView2 = (TextView) findViewById(R.id.avsure_text_lili);
		mView3 = (TextView) findViewById(R.id.avsure_text_paytime);
		mView4 = (TextView) findViewById(R.id.avsure_text_for);
		mView5 = (TextView) findViewById(R.id.avsure_text_longtime);
		mView6 = (TextView) findViewById(R.id.avsure_text_servicepay);
		mView7 = (TextView) findViewById(R.id.avsure_text_truemoney);
		mView1.setText(""+floatExtra);
		mView2.setText(""+floatExtra2);
		mView3.setText(""+intExtra);
		mView4.setText(""+forwhy);
		mView5.setText(""+intExtra2);
		mView6.setText(""+ervicefee);
		mView7.setText(""+shiji);
		
		
		mRelativ = (RelativeLayout) findViewById(R.id.avbosure_frame);
		
		findViewById(R.id.avborrowsure_image_back).setOnClickListener(this);
		findViewById(R.id.avborrowsure_text_xieyi).setOnClickListener(this);
		
		mTok = (TextView) findViewById(R.id.avborrowsure_text_ok);
		
		mBox = (CheckBox) findViewById(R.id.checkB_dsdf);
		mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
					mTok.setClickable(true);
				}else{
					mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
					mTok.setClickable(false);
				}
			}
		});
		mTok.setOnClickListener(this);
		mTok.setClickable(false);
	}
	
	private String upload1(ArrayList<String> uploadFiles, float allmoney,
			float floatExtra22, String forwhy1, int days, String makr1,int jklsd) {  
	      String end = "\r\n";  
	      String twoHyphens = "--";  
	      String boundary = "*****";  
	      String xmString= "" ;  
		  String xmlUTF8 = "";
		if(myApp.getDatas_load ()==null) return String.valueOf (false);
		  String getuser_id = myApp.getDatas_load().getId();
		    int userid = Integer.parseInt(getuser_id);
		    try {
				xmString = new String(jiekuanyontu.toString().getBytes("UTF-8"));
				xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");  
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}  
			try {
				URL url = new URL(HttpMethods.BASEURL+"g=api&m=quota&a=addPerson"
						+ "&quota_money="+allmoney + "&interest="+floatExtra22
						+ "&quota_use="+xmlUTF8 + "&repay_date="+days
						+ "&mark="+xmlUTF8 + "&exp_date="+jklsd
						+"&user_id="+userid+"&friends="+stringExtra); 
	          HttpURLConnection con = (HttpURLConnection) url.openConnection();  
	          con.setDoInput(true);  
	          con.setDoOutput(true);  
	          con.setUseCaches(false);  
	          con.setRequestMethod("POST");  
	          con.setRequestProperty("Connection", "Keep-Alive");  
	          con.setRequestProperty("Charset", "UTF-8");  
	          con.setRequestProperty("Content-Type",  
	                  "multipart/form-data;boundary=" + boundary);  
	          DataOutputStream ds =  
	                  new DataOutputStream(con.getOutputStream());  
	          for (int i = 0; i < uploadFiles.size(); i++) {  
	        	  String uploadFile = uploadFiles.get(i);
//					String filename = uploadFile.substring(uploadFile.lastIndexOf("\\") + 1); 
					ds.writeBytes(twoHyphens + boundary + end);
					ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file" + (i + 1) + "\";filename=\""+ "zhongcai" + i + ".jpg" + "\"" + end);
					ds.writeBytes(end);
					
					Mapupload maplos = new Mapupload();
					Bitmap getimage = maplos.getimage(uploadFile,1000);
					InputStream fStream = maplos.Bitmap2IS(getimage);
					if(fStream == null){
					}else{
					}
	              int bufferSize = 1024;  
	              byte[] buffer = new byte[bufferSize];  
	              int length = -1;  
	              while ((length = fStream.read(buffer)) != -1) {  
	                  ds.write(buffer, 0, length);  
	              }  
	              ds.writeBytes(end);  
	              fStream.close();  
	          }  
	          ds.writeBytes(twoHyphens + boundary + twoHyphens + end);  
	          ds.flush();  
	          InputStream is = con.getInputStream();  
	          int ch;  
	          StringBuffer b = new StringBuffer();  
	          while ((ch = is.read()) != -1) {  
	              b.append((char) ch);  
	          }  
	          String s = b.toString();
				Log.e("s", "s" + s);
				JSONObject json = new JSONObject(s);
				if(null != json.getString("flag") ){
					String string = json.getString("flag");
					if(string.equals("success")){
						isupload = true;
						}else{
							isupload = false;
						}		
					}
				ds.close();
			} catch (Exception e) {
				Log.e("e", "e" + e);
				Log.e("e2", "e2" + e.getMessage());
				isupload = false;
				e.printStackTrace();
			}
			return ""+isupload;
	  }
	
	class MyTask extends AsyncTask<String, Integer, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mRelativ.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected String doInBackground(String... params) {
			String upload = upload1(photolist, floatExtra, floatExtra2, forwhy, time1, forwhy,intExtra2);
			return upload;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(result.equals("true")){
				Toast.makeText(BorrowsureActivity.this, ""+getResources().getString(R.string.fabucgong), Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(BorrowsureActivity.this,PersonborrAcitivity.class);
				startActivity(intent);
				finish();
			}else{
				Toast.makeText(BorrowsureActivity.this, ""+getResources().getString(R.string.fabusbai), Toast.LENGTH_SHORT).show();
			}
			mRelativ.setVisibility(View.GONE);
		}
		
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avborrowsure_text_ok:
			jiekuanyontu = mView4.getText().toString().trim();
			if(shiji <= 0){
				Toast.makeText(BorrowsureActivity.this, ""+getResources().getString(R.string.chuxianfushu), Toast.LENGTH_SHORT).show();
			}else{
				MyTask myTask = new MyTask();
				myTask.execute("www.xinlang.com");
			}
//			ksjdlfkle(floatExtra,floatExtra2,intExtra,forwhy,intExtra2);
			break;
			
		case R.id.avborrowsure_image_back:
			finish();
			break;
			
		case R.id.avborrowsure_text_xieyi:
			ArrayList<String> lsit = new ArrayList<String>();
			lsit.add(""+floatExtra2);lsit.add(""+floatExtra);lsit.add(time);
			Intent intent = new Intent(BorrowsureActivity.this,YuqiActivity.class);
			intent.putExtra("list", lsit);
			startActivity(intent);
		finish();
		break;

		default:
			break;
		}
	}

	
}
